package cool.mtc.security.handler.auth;

import cool.mtc.security.auth.AuthFormSupport;
import cool.mtc.security.auth.AuthToken;
import cool.mtc.security.event.AuthFailureEvent;
import cool.mtc.security.event.AuthSuccessEvent;
import cool.mtc.web.util.HttpUtil;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;

import javax.servlet.http.HttpServletRequest;

/**
 * @author yz
 */
@Setter(onMethod = @__(@Autowired))
public class AuthHandler {
    private ApplicationEventPublisher eventPublisher;

    public void publishAuthSuccessEvent(HttpServletRequest request, AuthFormSupport authForm, AuthToken authToken) {
        if (null == eventPublisher) {
            return;
        }
        String ip = HttpUtil.getIP(request);
        String userAgent = HttpUtil.getUserAgent(request);

        AuthSuccessEvent event = new AuthSuccessEvent(this, ip, userAgent, authForm, authToken);
        eventPublisher.publishEvent(event);
    }

    public void publishAuthFailureEvent(HttpServletRequest request, AuthFormSupport authForm, String authWay, String description) {
        if (null == eventPublisher) {
            return;
        }
        String ip = HttpUtil.getIP(request);
        String userAgent = HttpUtil.getUserAgent(request);

        AuthFailureEvent event = new AuthFailureEvent(this, ip, userAgent, authForm, authWay, description);
        eventPublisher.publishEvent(event);
    }
}
